package net.gyapp.markim.module.basic.base;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;

import com.easyder.wrapper.base.presenter.MvpBasePresenter;
import com.easyder.wrapper.core.manager.DataManager;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.network.RequestInfo;
import com.easyder.wrapper.core.network.ResponseInfo;

import net.gyapp.markim.module.mine.account.LoginActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Author:  winds
 * Data:    2018/7/6
 * Version: 1.0
 * Desc:
 */


public class CommonPresenter extends MvpBasePresenter {

    public List<String> list = new ArrayList<>();

    @Override
    public void onError(ResponseInfo responseInfo) {
        if (isViewAttached()) {
            if (responseInfo.getUrl() != null) {
                if (list != null && list.size() > 0) {
                    for (String url : list) {
                        if (responseInfo.getUrl().contains(url)) {
                            requestCount--;
                            getView().onStopLoading();
                            getView().onError(responseInfo);
                            return;
                        }
                    }
                }
            }
        }
        super.onError(responseInfo);
    }

    @Override
    protected void login() {
        Context context = getView() instanceof Context ? (Context) getView() : ((Fragment) getView()).getContext();
        context.startActivity(LoginActivity.getIntent(context, true));
    }


    /**
     * 添加要过滤的url  添加后需要手动处理对应的onError方法
     * @param url
     */
    public void addFiltersUrl(String url) {
        if (!list.contains(url)) {
            list.add(url);
        }
    }

    public void clearFiltersUrl() {
        list.clear();
    }

    public void removeFiltersUrl(String url) {
        list.remove(url);
    }

    /**
     * Post请求
     *
     * @param url
     * @param params    参数
     * @param dataClass 对象类型
     */
    public void postJsonData(String url, ArrayMap<String, Serializable> params, Class<? extends BaseVo> dataClass) {
        if (isViewAttached() && needDialog && requestCount >= 0) {
            getView().onLoading();
        }
        RequestInfo requestInfo = new RequestInfo(url, dataClass);
        requestInfo.setRequestType(RequestInfo.REQUEST_POST_JSON);
        requestInfo.setRequestParams(params);
        DataManager.getDefault().loadData(requestInfo, this);
        requestCount++;
    }
}
